﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.helper;
using S.Parturition.API.Application.Command;
using S.Parturition.API.Dto;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Infrastructure.Interface;

namespace S.Parturition.API.Application.CommandHandlers
{
    /// <summary>
    /// 修改种母分娩具体实现
    /// </summary>
    public class ParturitionUpdateHandler : IRequestHandler<ParturitionUpdateCommand, bool>
    {
        private readonly IParturitionRepository repository;

        private readonly IMapper mapper;

        private readonly MyDbContext dbContext;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public ParturitionUpdateHandler(IParturitionRepository repository, IMapper mapper, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        public async Task<bool> Handle(ParturitionUpdateCommand request, CancellationToken cancellationToken)
        {
            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    //获取到apollo上的网关地址
                    string Gateway = configuration.GetValue<string>("Gateway");


                    #region 修改妊检记录

                    ParturitionModel parturition = mapper.Map<ParturitionModel>(request);

                    parturition.UpdateDate = DateTime.Now;

                    await repository.UpdateAsync(parturition);

                    #endregion

                    #region 反填并修改种母历史记录

                    EditBreed editBreed = new()
                    {
                        EarTag = parturition.EarTag
                    };

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    //判断是否获取到种母历史记录信息
                    if (string.IsNullOrWhiteSpace(jsonString))
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    //修改种母历史记录
                    response.DeliveryDate = parturition.DeliveryDate;
                    response.IsEditor = true;
                    var breeding = HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    if (breeding == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 修改档案信息

                    var archives = EditReproductivePresenceState.UpdateReproductivePresenceState(parturition.EarTag, 1, 8, parturition.DeliveryDate, Gateway);
                    if (archives == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }
                    #endregion


                    //事物执行
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    //事物回滚
                    tran.Rollback();

                    return false;
                }
            }
        }

        public class EditBreed
        {
            /// <summary>
            /// 可视耳号
            /// </summary>
            public string? EarTag { get; set; }
        }

    }
}
